package com.lyn.solitude.pluginhost.provider

import android.app.Application
import android.app.Service
import android.content.ComponentName
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Intent
import android.content.ServiceConnection
import android.database.Cursor
import android.net.Uri
import android.os.IBinder
import android.util.Log
import com.lyn.solitude.api.PluginHostAidl
import com.lyn.solitude.pluginhost.PluginManager
import com.lyn.solitude.pluginhost.service.PluginService

/**
 *
 * @author longyn 2024/05/22
 * @version 1.0.0
 */
class PluginProvider : ContentProvider() {

    companion object {
        const val TAG = "PluginProvider"
    }


    override fun onCreate(): Boolean {
        val applicationContext = context!!.applicationContext
        PluginManager.initialize(applicationContext as Application)
        applicationContext.bindService(
            Intent(applicationContext, PluginService::class.java), serviceConnection,
            Service.BIND_AUTO_CREATE
        )
        return true
    }

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            PluginManager.pluginHostAidl = PluginHostAidl.Stub.asInterface(service)
            Log.d(TAG, "onServiceConnected")
            PluginManager.pluginListenerAidl?.let {
                PluginManager.pluginHostAidl?.setPluginListenerAidl(it)
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d(TAG, "onServiceDisconnected")
            PluginManager.application.bindService(
                Intent(PluginManager.application, PluginService::class.java), this,
                Service.BIND_AUTO_CREATE
            )
        }

    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        return null
    }

    override fun getType(uri: Uri): String? {
        return null
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        return null
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        return 0
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        return 0
    }
}